package com.gzhu.knowledgeAdmin.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzhu.knowledgeAdmin.entity.Scene;
import com.gzhu.knowledgeAdmin.service.SceneService;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 场景列表导入处理器
 * @author yangminggui
 * @create 2024-04-18 17:18
 */
public class ScenceImportHandler extends MyImportHandler {

    SceneService sceneService;

    String gsid;


    // 导入返回信息
    StringBuilder stringBuilder = new StringBuilder();

    List<Scene> sceneList;

    public ScenceImportHandler(String gsid,List<Scene> sceneList) {
        this.sceneService = SpringUtil.getBean(SceneService.class);;
        this.gsid = gsid;
        this.sceneList = sceneList;
    }


    private String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入场景结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, stringBuilder.toString());
        return summaryMsg;
    }

    @Override
    public String handle() {

        for (Scene scene : sceneList) {

            String name = scene.getName();

            StringBuilder validationMsg = new StringBuilder();

            // 名称是否为空
            if(!StringUtils.hasLength(name)){
                validationMsg.append("场景名称为空");
            }else {
                // 判断场景名字是否重复
                int count = sceneService.count(new QueryWrapper<Scene>().eq("name", name).eq("gsid", gsid));
                if (count > 0) {
                    validationMsg.append("场景名称已存在");
                }
            }

            if(validationMsg.length()==0){
                // 设置公司id
                scene.setGsid(gsid);
                boolean save = sceneService.save(scene);

                // 插入异常
                if(!save){
                    invalidCount++;
                    stringBuilder.append("第").append(validCount + invalidCount).append("行数据保存失败；<br/>");
                }else {
                    validCount++;
                }
            }else { // 验证错误

                invalidCount++;
                stringBuilder.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(validationMsg + "<br/>");
            }

        }

        return getMsg();

    }
}
